package com.yami.shop.platform.task;

import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.model.VrSceneTrigger;
import com.yami.shop.common.bean.TencentSMS;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.config.ShopConfig;
import com.yami.shop.config.WxConfig;
import com.yami.shop.service.SysConfigService;
import com.yami.shop.service.VrSceneTriggerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.*;


/**
 * @author yami
 */
@Component
public class NotifyVrSceneTask {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private VrSceneTriggerService vrSceneTriggerService;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private ShopConfig shopConfig;
    @Autowired
    private SysConfigService sysConfigService;
    @XxlJob("sendVrSceneMessage")
    public void sendVrSceneMessage(){
        logger.info("获取还未进行消息推送的通知。。。");
        // 获取还未进行消息推送的通知
        List<VrSceneTrigger> list = vrSceneTriggerService.getList();
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        // 推送消息
        for (VrSceneTrigger vrSceneTrigger:list) {
            try {
                Integer remindType = sendMpMessage(vrSceneTrigger);
                vrSceneTrigger.setStatus("2");
                vrSceneTrigger.setRemindType(remindType);
                vrSceneTrigger.setUpdateTime(new Date());
            }catch (Exception e){
                vrSceneTrigger.setStatus("4");
                vrSceneTrigger.setUpdateTime(new Date());
            }
        }
        vrSceneTriggerService.updateBatchById(list);
    }
    private Integer sendMpMessage(VrSceneTrigger vrSceneTrigger ) {
        try {
            if("2".equals(vrSceneTrigger.getWxMsnAuth())){//未授权
                throw new RuntimeException("未授权");
            }
            //小程序发送消息
            WxMaSubscribeMessage subscribeMessage = new WxMaSubscribeMessage();
            //跳转小程序页面路径
            subscribeMessage.setPage("pages/index/index?id="+vrSceneTrigger.getRightsId()+"&name="+vrSceneTrigger.getRightsName());
            //模板消息id
            subscribeMessage.setTemplateId(vrSceneTrigger.getTemplateId());
            //给谁推送 用户的openid （可以调用根据code换openid接口)
            subscribeMessage.setToUser(vrSceneTrigger.getOpenId());

            WxMaSubscribeMessage.MsgData wxMaSubscribeData =  new WxMaSubscribeMessage.MsgData();
            wxMaSubscribeData.setName("thing1");
            wxMaSubscribeData.setValue(vrSceneTrigger.getRightsName());
            subscribeMessage.addData(wxMaSubscribeData);
            WxMaSubscribeMessage.MsgData wxMaSubscribeData2 =  new WxMaSubscribeMessage.MsgData();
            wxMaSubscribeData2.setName("thing2");
            wxMaSubscribeData2.setValue("进入小程序领取");
            subscribeMessage.addData(wxMaSubscribeData2);
            wxConfig.getWxMaService().getMsgService().sendSubscribeMsg(subscribeMessage);
            return 2;
        } catch (Exception e) {
            //失败异常 发短信
            TencentSMS tencentSMS = null;
            try {
                tencentSMS = shopConfig.getTencentSms();
            }catch (Exception ec){
                sysConfigService.removeSysConfig(Constant.TENCENTSMS_CONFIG);
                tencentSMS = shopConfig.getTencentSms();
            }
            //测试号码
            String smsWhitelist = shopConfig.getSmsWhitelist();
            if (ObjectUtil.isNotEmpty(smsWhitelist) && matches(vrSceneTrigger.getPhone(), Arrays.asList(smsWhitelist.split(",")))) {
                logger.info("白名单发送");
            }else{
                //正式号码发送短信
                SmsSingleSender sender = new SmsSingleSender(tencentSMS.getAppId(), tencentSMS.getApikey());
                //参数转换
                ArrayList<String> parms = new ArrayList<>();
                parms.add(vrSceneTrigger.getRightsName());//模板参数 权益名称
                Integer templateCode = 12;//短信模板
                SmsSingleSenderResult result = null;
                try {
                    result = sender.sendWithParam("86", vrSceneTrigger.getPhone(), templateCode, parms, tencentSMS.getSmsSign(), "", "");
                } catch (Exception ex) {
                    throw new YamiShopBindException("短信发送失败");
                }
                if (!"OK".equals(result.errMsg)) {
                    throw new YamiShopBindException("短信发送失败");
                }
                logger.info("发送成功");
            }
            return 1;
        }
    }
    /**
     * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串
     *
     * @param str 指定字符串
     * @param strs 需要检查的字符串数组
     * @return 是否匹配
     */
    private  boolean matches(String str, List<String> strs)
    {
        if (ObjectUtil.isEmpty(str) || ObjectUtil.isEmpty(strs))
        {
            return false;
        }
        for (String pattern : strs)
        {
            if (isMatch(pattern, str))
            {
                return true;
            }
        }
        return false;
    }
    private boolean isMatch(String pattern, String url)
    {
        AntPathMatcher matcher = new AntPathMatcher();
        return matcher.match(pattern, url);
    }

}
